<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title>分类管理</title>
        <meta name="renderer" content="webkit">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="/static/admin/component/elementui/index.min.css">
        <style>
            .elform-editor .el-form-item__content {
                margin-left: 0 !important;
            }
        </style>
    </head>

    <body>
        <div id="app" style="padding: 16px;">
            <div class="layui-card">
                <div class="layui-card-body">
                    <!-- element表格 -->
                    <el-row style="margin-top: 15px;">
                        <el-row style="margin-bottom: 5px;">
                            <el-button type="primary" size="small" @click="showAddModal()">添加分类</el-button>
                            <el-button @click="deleteCategoryBatch" type="danger" size="small">批量删除</el-button>
                        </el-row>

                        <el-table :data="tableData" size="small" border style="width: 100%"
                            @selection-change="handleSelectionChange">
                            <el-table-column align="center" type="selection" width="50">
                            </el-table-column>
                            <el-table-column align="center" prop="id" label="ID" width="80">
                            </el-table-column>
                            <el-table-column :fit="true" align="center" prop="name" label="分类名称">
                            </el-table-column>

                            <el-table-column align="center" fixed="right" label="操作" width="100">
                                <template slot-scope="scope">
                                    <el-button type="text" size="small" @click="showEditModal(scope.row)">编辑</el-button>
                                    <el-button type="text" size="small" style="color: red;"
                                        @click="deleteCategory(scope.row.id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                    </el-row>

                    <!-- 添加分类表单对话框 -->
                    <el-dialog title="添加" :visible.sync="addFormVisible" :modal="false"
                     :close-on-click-modal="false" :close-on-press-escape="true" :destroy-on-close="true">
                        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="80px">
                            <!-- 分类名称 -->
                            <el-form-item label="分类名称" prop="name">
                                <el-input v-model="addForm.name" clearable></el-input>
                            </el-form-item>
                        </el-form>

                        <div slot="footer" class="dialog-footer">
                            <el-button size="small" @click="addFormVisible = false">取消</el-button>
                            <el-button size="small" type="primary" @click="addCategory()">确定</el-button>
                        </div>
                    </el-dialog>


                    <!-- 编辑分类表单对话框 -->
                    <el-dialog title="编辑" :visible.sync="editFormVisible" :modal="false"
                     :close-on-click-modal="false" :close-on-press-escape="true" :destroy-on-close="true">
                        <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="80px">
                            <!-- 分类名称 -->
                            <el-form-item label="分类名称" prop="name">
                                <el-input v-model="editForm.name" clearable></el-input>
                            </el-form-item>
                        </el-form>

                        <div slot="footer" class="dialog-footer">
                            <el-button size="small" @click="editFormVisible = false">取消</el-button>
                            <el-button size="small" type="primary" @click="updateCategory()">确定</el-button>
                        </div>
                    </el-dialog>

                </div>
            </div>
        </div>



        <script src="/static/admin/component/elementui/vue.min.js"></script>
        <script src="/static/admin/component/elementui/index.min.js"></script>

        <script type="text/javascript">
            new Vue({
                el: '#app',
                data: {
                    // 分类列表数据
                    tableData: [],
                    // 多选框选中数据
                    multipleSelection: [],
                    // 添加分类表单对话框是否可见
                    addFormVisible: false,
                    // 添加分类表单
                    addForm: {
                        name: '',
                    },
                    // 添加分类表单验证规则
                    addFormRules: {
                        name: [
                            { required: true, message: '请输入分类名称', trigger: 'blur' },
                        ],
                    },

                    // 编辑分类表单对话框是否可见
                    editFormVisible: false,
                    // 编辑分类表单
                    editForm: {
                        id: 0,
                        name: '',
                    },
                    // 编辑分类表单验证规则
                    editFormRules: {
                        name: [
                            { required: true, message: '请输入分类名称', trigger: 'blur' },
                        ],
                    },
                },
                methods: {
                    // 批量删除分类
                    deleteCategoryBatch() {
                        if (!this.multipleSelection || this.multipleSelection.length === 0) {
                            return this.$message.warning('请选择要删除的分类');
                        }

                        this.$confirm('确定删除选中的分类吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            let ids = [];
                            this.multipleSelection.forEach(item => {
                                ids.push(item.id);
                            });

                            // 提交批量删除
                            fetch("/admin/category/batchDelete", {
                                method: "POST",
                                headers: {
                                    "Accept": 'application/json',
                                    "Authorization": sessionStorage.getItem('token') || '',
                                    "Content-Type": 'application/json;charset=UTF-8'
                                },
                                body: JSON.stringify({
                                    ids: ids,
                                }),
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error(res.msg);
                                    }

                                    this.$message.success('操作成功!');
                                    // 重新加载列表
                                    this.getCategoryList();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });

                        })
                    },

                    // 多选框选择事件
                    handleSelectionChange(val) {
                        this.multipleSelection = val;
                    },

                    // 行删除分类
                    deleteCategory(id) {
                        this.$confirm('确定删除该分类吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            // 提交删除
                            fetch(`/admin/category/delete/${id}`, {
                                method: "DELETE",
                                headers: {
                                    "Accept": 'application/json',
                                    "Authorization": sessionStorage.getItem('token') || '',
                                }
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error(res.msg);
                                    }

                                    this.$message.success('操作成功!');
                                    // 重新加载列表
                                    this.getCategoryList();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });
                        })
                    },

                    // 显示添加分类弹窗
                    showAddModal() {
                        this.addFormVisible = true;
                    },
                    // 提交添加分类
                    addCategory() {
                        // 表单验证
                        this.$refs.addForm.validate(valid => {
                            if (!valid) {   // 表单验证不通过
                                return this.$message.warning('请填输入分类名称！');
                            }

                            fetch(`/admin/category/add`, {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json;charset=UTF-8",
                                    "Authorization": sessionStorage.getItem('token') || '',
                                },
                                body: JSON.stringify(this.addForm),
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error('操作失败！');
                                    }

                                    this.$message.success('操作成功！');
                                    this.$refs.addForm.resetFields();   // 重置表单
                                    this.addFormVisible = false;
                                    // 刷新分类列表
                                    this.getCategoryList();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });
                        });
                    },

                    // 显示编辑分类弹窗
                    showEditModal(row) {
                        this.editForm = row;
                        this.editFormVisible = true;
                    },
                    
                    // 提交编辑分类
                    updateCategory() {
                        // 表单验证
                        this.$refs.editForm.validate(valid => {
                            if (!valid) {   // 表单验证不通过
                                return this.$message.warning('请填写完整！');
                            }

                            fetch(`/admin/category/edit/${this.editForm.id}`, {
                                method: "PUT",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json;charset=UTF-8",
                                    "Authorization": sessionStorage.getItem('token') || '',
                                },
                                body: JSON.stringify(this.editForm),
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error('操作失败！');
                                    }

                                    this.$message.success('操作成功！');
                                    this.editFormVisible = false;
                                    // 刷新分类列表
                                    this.getCategoryList();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });
                        });
                    },


                    // 获取分类列表
                    getCategoryList() {
                        fetch('/admin/category/list', {
                            method: "GET",
                            headers: {
                                "Accept": 'application/json',
                                "Authorization": sessionStorage.getItem('token') || '',
                            },
                        })
                            .then((response) => response.json())
                            .then(res => {
                                if (res.code != 200) {
                                    return this.$message.error(res.msg);
                                }

                                this.tableData = res.data;
                            })
                            .catch((err) => {
                                console.error("Error:", err);
                            });
                    },

                },
                mounted() {
                    // 获取分类列表
                    this.getCategoryList();
                    
                }
            });

        </script>
    </body>

</html>